package com.longwang.controller;

import com.github.pagehelper.PageInfo;
import com.longwang.common.Constant;
import com.longwang.common.Result;
import com.longwang.entity.*;
import com.longwang.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前台 -- 文章控制器
 * @author longwang
 * @create 2018-10-25 17:52
 */
@Controller
@RequestMapping("/resouceContent")
public class ResouceContentController {

    @Autowired
    private ITemplateEngine templateEngine;

    @Autowired
    private IResouceContentService iResouceContentService;

    @Autowired
    private IResouceCatalogService iResouceCatalogService;

    @Autowired
    private IResouceLableService iResouceLableService;

    @Autowired
    private IResouceLableContentService iResouceLableContentService;

    @Autowired
    private IResouceVideoService iResouceVideoService;

    @Autowired
    private IResouceDownloadFileService iResouceDownloadFileService;

    @Value("${downloadFilePath}")
    private String downloadFilePath;  // 文件下载路径




    /**
     * 分页带条件查询
     * @param resouceContent  条件
     * @param pageNum  当前页
     * @param pageSize  每页记录数
     * @return
     */
    @RequestMapping("/indexList")
    @ResponseBody
    public Map<String, Object> indexList(HttpServletRequest request, HttpServletResponse response, ResouceContent resouceContent, @RequestParam(name = "lableId",required = false) Long lableId, Integer pageNum, Integer pageSize, ModelMap modelMap){
        Map<String, Object> resultMap = new HashMap<>();
        resouceContent.setIsShow(1);  // 只查显示的
        resouceContent.setIsHome(1);  // 只查首页显示的
        WebContext context = new WebContext(request, response, request.getServletContext());
        if(lableId == null){
            Result<PageInfo<ResouceContent>> all = iResouceContentService.findAll(resouceContent, pageNum, pageSize);
            context.setVariable("data", all);
            resultMap.put("pages", all.getData().getPages());
        }else{
            List<Long> allByLableId = iResouceLableContentService.findAllByLableId(lableId).getData();
            Result<PageInfo<ResouceContent>> allById = iResouceContentService.findAllById(allByLableId, pageNum, pageSize);
            context.setVariable("data", allById);
            resultMap.put("pages", allById.getData().getPages());
        }
        resultMap.put("htmlStr", templateEngine.process("article/list",context));
        return resultMap;
    }

    @RequestMapping("/index/{siteType}")
    public String index(@PathVariable(value="siteType",required=false)Integer siteType, ModelMap modelMap){
        modelMap.put("oneCatalogList",iResouceCatalogService.findAll(siteType).getData());
        modelMap.put("lableList",iResouceLableService.findAll(new ResouceLable(siteType),1,50).getData().getList());
        modelMap.put("siteType",siteType);
        return "article/index";
    }

    /**
     * 分页带条件查询
     * @param pageNum  当前页
     * @param pageSize  每页记录数
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request, HttpServletResponse response,Integer catalogId, ResouceContent resouceContent,Integer pageNum, Integer pageSize){
        Map<String, Object> resultMap = new HashMap<>();
        WebContext context = new WebContext(request, response, request.getServletContext());
        List<ResouceCatalog> data = iResouceCatalogService.findAllByClassPid(catalogId).getData();
        if(data.size() > 0){
            Long[] catalogIds= new Long[data.size()];
            for (int i = 0; i < catalogIds.length; i++)
                catalogIds[i] = data.get(i).getId();
            resouceContent.setCatalogIds(catalogIds);
        }
        resouceContent.setIsShow(1);
        Result<PageInfo<ResouceContent>> all = iResouceContentService.findAll(resouceContent, pageNum, pageSize);
        context.setVariable("data", all);
        Integer siteType = resouceContent.getSiteType();
        if(siteType == Constant.SiteType.WEN_ZHANG)
            resultMap.put("htmlStr", templateEngine.process("article/articleList",context));
        if(siteType == Constant.SiteType.SHI_PIN)
            resultMap.put("htmlStr", templateEngine.process("article/videoList",context));
        if(siteType == Constant.SiteType.RUAN_JIAN)
            resultMap.put("htmlStr", templateEngine.process("article/fileList",context));
        resultMap.put("pages", all.getData().getPages());
        return resultMap;
    }

    /**
     * 点击标签页
     * @return
     */
    @RequestMapping("/lable/{id}")
    public String index(@PathVariable(value = "id")Long id,ModelMap modelMap){
        Result<ResouceLable> byId = iResouceLableService.findById(id);
        modelMap.put("resouceLable", byId.getData());
        return "lable/index";
    }

    @RequestMapping("/details/{id}")
    public String details(@PathVariable(value="id")Long id, ModelMap modelMap){
        ResouceContent data = iResouceContentService.findById(id).getData();
        if(data.getSiteType() == Constant.SiteType.SHI_PIN){
            Result<List<ResouceVideo>> allByContentId = iResouceVideoService.findAllByContentId(data.getId());
            modelMap.put("resouceVideoList",allByContentId.getData());
        }
        if(data.getSiteType() == Constant.SiteType.RUAN_JIAN){
            Result<ResouceDownloadFile> allByContentId = iResouceDownloadFileService.findAllByContentId(data.getId());
            modelMap.put("resouceDownloadFile",allByContentId.getData());
        }
        modelMap.put("lableList",iResouceLableService.findAll(new ResouceLable(data.getSiteType()),1,50).getData().getList());
        modelMap.put("resouceContent",data);
        return "article/details";
    }

    @RequestMapping("/download/{id}")
    public ResponseEntity<byte[]> download(@PathVariable(value="id")Long id) throws IOException {
        ResouceDownloadFile resouceDownloadFile = iResouceDownloadFileService.findById(id).getData();
        resouceDownloadFile.setDownloadCount(Long.valueOf(resouceDownloadFile.getDownloadCount() + 1L));
        iResouceDownloadFileService.save(resouceDownloadFile);
        HttpHeaders headers = new HttpHeaders();
        File file = new File(downloadFilePath + resouceDownloadFile.getUrl());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", resouceDownloadFile.getFileName());
        return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

}
